#+_+ coding:utf-8 +_+

import redis
from common import utils

proxy = redis.StrictRedis(host='localhost', port=6379, db=0)

def GenerateID():
    rst = proxy.incr("id_generator")
    return int(rst)

def GenerateNewsID():
    rst = proxy.incr("news_id_generator")
    return int(rst)

def GenerateCommentID():
    rst = proxy.incr("comment_id_generator")
    return int(rst)

def AppendNewsID(id):
    rst = proxy.lpush("news",id)
    return rst

def GetNewsIDs(index,count):
    rst = proxy.lrange("news",index,str(int(count)-1))
    return rst

def GetNews(id):
    key = "news:"+str(id)
    title = proxy.hget(key,"title")
    author = proxy.hget(key,"author")
    timestmp = int(float(proxy.hget(key,"timestmp")))
    content = proxy.hget(key,"content")
    star = int(proxy.hget(key,"star"))
    return dict(id=id,author=author,time=timestmp,title=title,content=content,star=star)

def GenerateCommentID():
    rst = proxy.incr("comment_id_generator")
    return rst

def AddComment(uid,newsID,commentID,author,comment,timestmp):
    key = "comment:"+str(commentID)
    rst = proxy.hmset(key,dict(uid=uid,author=author,comment=comment,timestmp=timestmp))
    key = "news_comments:"+str(newsID)
    rst = proxy.lpush(key,commentID)

def GetComments(newsID):
    key = "news_comments:"+str(newsID)
    length = proxy.llen(key)
    rst = proxy.lrange(key,0,length-1)
    return rst

def GetComment(commentID):
    key = "comment:"+str(commentID)
    author = proxy.hget(key,"author")
    timestmp = int(float(proxy.hget(key,"timestmp")))
    content = proxy.hget(key,"content")
    return dict(author=author,timestmp=timestmp,comment=content)

def CheckCommentID(id):
    key = "comment:"+str(id)
    rst = proxy.exists(key)
    return rst

def ExistsNews(id):
    key = "news:"+str(id)
    rst = proxy.exists(key)
    return rst

def AddNews(id,author,timestmp,title,content):
    key = "news:"+str(id)
    rst = proxy.hmset(key,dict(star=0,author=author,timestmp=timestmp,title=title,content=content))
    return rst

def UpdateIDTicket(uid,ticket):
    key = "uid:"+str(uid)
    rst = proxy.set(key,ticket,ex=utils.TICKET_TIMEOUT)
    return rst

def GetTicket(uid):
    key = "uid:"+str(uid)
    rst = proxy.get(key)
    return rst

def EnqueueID(id):
    rst = False
    try:
        proxy.rpush("ids",int(id))
        rst = True
    except Exception as e:
        rst = False
    return rst

def StoreNews(news):
    c = dict(author=news._author,
             time=news._time,
             start=news._star,
             title=news._title,
             content = news._content )
    key = "news:"+str(news._id)
    rst = proxy.hmset(key,c)

